package DSPackage;

import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.content.*;
import jade.content.lang.sl.*;
import jade.content.onto.basic.*;
import jade.domain.*;
import jade.domain.mobility.*;
import jade.domain.JADEAgentManagement.*;

import jade.domain.FIPAAgentManagement.*;


public class DSAgent extends Agent {
// ----------------------------------------

    // Search the AMS for agents to access
    AMSAgentDescription [] fsAgent = null;
    private AID dsID;
    transient protected DSAgent myGui;

    protected void setup() {
    // ------------------------

        // Retrieve arguments passed during this agent creation
        dsID = getAID();

        init();

        try {
            // Finding all known agents
            SearchConstraints c = new SearchConstraints();
            c.setMaxResults(new Long(-1));
            fsAgent = AMSService.search(this, new AMSAgentDescription (), c );
        }
        catch (Exception e) {
            e.toString();
        }

        // Program the main behaviour of this agent
        addBehaviour(new MoveAccBW(this));
    }

    void init() {
          // Register language and ontology
          getContentManager().registerLanguage(new SLCodec());
          getContentManager().registerOntology(MobilityOntology.getInstance());

          // Create and display the gui
          myGui = new DSAgent();
    }

    protected void beforeMove() {

    }

    protected void afterMove() {
          init();
    }




/*
* Receive all commands from the controller agent
*/
class MoveAccBW extends SimpleBehaviour {

    private boolean finished = false;

    public MoveAccBW(Agent a) {
        super(a);
    }

    public void action() {

        for (int i=0 ; i < fsAgent.length ;i++)
        {
            AID agentID = fsAgent[i].getName();
            System.err.println("Server: " + fsAgent[i].getName().toString());
        }

        ACLMessage msg = receive(MessageTemplate.MatchSender(dsID));

        try {
            ContentElement content = getContentManager().extractContent(msg);
            Concept concept = ((Action)content).getAction();

            if (concept instanceof MoveAction){
                
                MobileAgentDescription mad = new MobileAgentDescription();
                mad.setDestination(here());

                MoveAction ma = new MoveAction();
                ma.setMobileAgentDescription(mad);
                Location l = ma.getMobileAgentDescription().getDestination();

                if (l != null) doMove(l);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        finished = true;

    }

    @Override
    public boolean done() {
        return finished;
    }
}
}